package com.lqq.school.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @GetMapping("/toLogin")
    public String toLogin() {
        return "index";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password")String password,
                        Model model,
                        HttpSession session) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();

        // public UsernamePasswordToken(String username, char[] password) {
        // this(username, (char[])password, false, (String)null);}

        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);//执行登陆的方法
        }catch (UnknownAccountException e) {
            model.addAttribute("msg", "账户不存在！！！");//用户名不存在
            return "index";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误！！！");//密码不存在
            return "index";
        }
        //管理员
        if (username.equals("admin")) {
            session.setAttribute("username", username);
            return "redirect:/admin/main";
        }

        else {
            //普通用户
            session.setAttribute("username", username);
            return "redirect:/stu/main";
        }
    }

    //登录url映射
    //学生仔登录
    @GetMapping("/stu/main")
    public String stuMain(){
        return "/stu/dashboard";
    }

    //管理员登录
    @GetMapping("/admin/main")
    public String adminMain(){
        return "/admin/dashboard";
    }
}